package com.google.code.synchronized_player;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

import android.content.Context;
import android.util.Log;

public class PlayList {
	private Context context;
	private ArrayList<Track> tracks = new ArrayList<Track>();
	private File playListFile;
	
	public PlayList(Context context) {
		this.context = context;
		File cacheDir;
		if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            cacheDir = context.getCacheDir();//new File(android.os.Environment.getExternalStorageDirectory(),"vk.messenger");
		} else {
            cacheDir = context.getCacheDir();
		}
        if(!cacheDir.exists())
            cacheDir.mkdirs();
        playListFile = new File(cacheDir, "playlist.m3u");
        if(!playListFile.exists()) {
        	writePlayList();
        }
        readPlayList();
        Log.d("vk", cacheDir.getPath());
	}
	
	final ArrayList<Track> getTracksList() {
		return tracks;
	}
	
	void addTrack(String path) {
		tracks.add(new Track(path));
		writePlayList();
	}

	void removeTrack(String path) {
	}

	private void readPlayList() {
		try {
			Scanner sc = new Scanner(playListFile);
			sc.nextLine();
			sc.nextLine();
			while(sc.hasNext()) {
				String trackname = sc.nextLine();
				tracks.add(new Track(trackname));
			}
			sc.close();
		} catch(FileNotFoundException fnfex) {
			Log.d("PlayList", "File not found exception");			
		}
	}
	
	private void writePlayList() {
		try {
			PrintWriter outStream = new PrintWriter(playListFile);
			outStream.println("#EXTM3U\n");
			for(Track cur: tracks) {
				outStream.println(cur.name);
			}
			outStream.close();
		} catch(FileNotFoundException fnfex) {
			Log.d("PlayList", "File not found exception");			
		}
	}
}
